//
//  MusicPalyViewController.m
//  CCBbelefitLife
//
//  Created by 小晓 on 16/1/10.
//  Copyright © 2016年 liurg. All rights reserved.
//

#import "MusicPalyViewController.h"
#import "Music.h"

@interface MusicPalyViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    AVAudioPlayer *audioPlayer;
    NSMutableArray *musicArray;
    BOOL isPlay;
    BOOL isCircle;
    BOOL musicTableViewHidden;
    float tempVolume;
    Music *currentMusic;
    NSMutableArray *timeArray;
    NSMutableDictionary *LRCDictionary;
    NSUInteger lrcLineNumber;
    NSUInteger musicArrayNumber;
    UIButton * circleBtn;
    UIButton *playBtn;
    UISlider * progressSlider;
//    UITableView *musicTableView;
}

@end

@implementation MusicPalyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupView];
    isPlay = YES;
    isCircle = YES;
    lrcLineNumber = 0;
    musicTableViewHidden = YES;//初始化隐藏歌曲目录
//    musicTableView.hidden = YES;
    
    //初始化要加载的曲目
    [self initDate];
    musicArrayNumber = 0;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[musicArray[musicArrayNumber] name] ofType:@"mp3"]] error:nil];
    currentMusic = musicArray[musicArrayNumber];
    
    //初始化音量和音量进度条
    audioPlayer.volume = 0.1;
    _soundSlider.value = audioPlayer.volume;
    [_soundSlider setThumbImage:[UIImage imageNamed:@"soundSlider.png"] forState:UIControlStateNormal];
    [_soundSlider setThumbImage:[UIImage imageNamed:@"soundSlider.png"] forState:UIControlStateHighlighted];
    //    soundSlider.hidden = YES;
    
    //初始化歌词词典
    timeArray = [[NSMutableArray alloc] initWithCapacity:10];
    LRCDictionary = [[NSMutableDictionary alloc] initWithCapacity:10];
    
    //初始化播放进度条
    [progressSlider setThumbImage:[UIImage imageNamed:@"sliderThumb_small.png"] forState:UIControlStateNormal];
    [progressSlider setThumbImage:[UIImage imageNamed:@"sliderThumb_small.png"] forState:UIControlStateHighlighted];
    
    [self initLRC];
    //设置监控 每秒刷新一次时间
    [NSTimer scheduledTimerWithTimeInterval:0.1f
                                     target:self
                                   selector:@selector(showTime)
                                   userInfo:nil
                                    repeats:YES];
    [self buildNavView];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
     self.tabBarController.tabBar.hidden = YES;
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

-(void)buildNavView{
    //导航栏右侧按钮
//    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    leftBtn.frame = CGRectMake(0, 30, 30, 20);
//    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back-arrow.png"] forState:UIControlStateNormal];
//    [leftBtn addTarget:self
//                action:@selector(backBtnAction)
//      forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:leftBtn];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"back" highIcon:@"back" target:self action:@selector(backBtnAction)];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
//    self.navigationItem.leftBarButtonItem = leftItem;
    
}


-(void)backBtnAction{
    [self.navigationController popViewControllerAnimated:YES];
    //  [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

-(void)setupView{
    
    [self.navigationController setNavigationBarHidden:YES animated:TRUE];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];

   // self.navigationController.navigationBar.alpha = 1.0;
    UIView * upView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, mainScreenWidth, 200)];
    upView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"图层-24@2x.png"]];
    [self.view addSubview:upView];
    
    _lrcTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 80, mainScreenWidth, 60) style:(UITableViewStylePlain)];
    _lrcTableView.backgroundColor = [UIColor clearColor];
    [_lrcTableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    _lrcTableView.delegate = self;
    _lrcTableView.dataSource = self;
    [upView addSubview:_lrcTableView];
    
    UIView * playView = [[UIView alloc]initWithFrame:CGRectMake(0, 140, mainScreenWidth, 60)];
    playView.alpha = 0.7;
    playView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"图层-10@2x.png"]];
    [upView addSubview:playView];
    
    progressSlider = [[UISlider alloc]initWithFrame:CGRectMake(0, -5, mainScreenWidth, 10)];
    progressSlider.value = 0.0;
    [progressSlider setThumbImage:[UIImage imageNamed:@"sliderThumb_small.png"] forState:UIControlStateNormal];
    [progressSlider setThumbImage:[UIImage imageNamed:@"sliderThumb_small.png"] forState:UIControlStateHighlighted];
    [playView addSubview:progressSlider];
    
    circleBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 15, 39, 30)];
    [circleBtn setBackgroundImage:[UIImage imageNamed:@"circleOpen.png"] forState:(UIControlStateNormal)];
    [circleBtn addTarget:self action:@selector(circle:) forControlEvents:(UIControlEventTouchUpInside)];
    [playView addSubview:circleBtn];
    
    playBtn = [[UIButton alloc]initWithFrame:CGRectMake(mainScreenWidth*0.5-26, 5, 62, 50)];
    [playBtn setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:(UIControlStateNormal)];
    [playBtn addTarget:self action:@selector(play:) forControlEvents:(UIControlEventTouchUpInside)];
    [playView addSubview:playBtn];
    
    _currentTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(mainScreenWidth-50, 20, 50, 20)];
    _currentTimeLabel.text = @"00:00";
    [playView addSubview:_currentTimeLabel];
}

#pragma mark 0.1秒一次更新 播放时间 播放进度条 歌词 歌曲 自动播放下一首
- (void)showTime {
    //动态更新进度条时间
    if ((int)audioPlayer.currentTime % 60 < 10) {
        _currentTimeLabel.text = [NSString stringWithFormat:@"%d:0%d",(int)audioPlayer.currentTime / 60, (int)audioPlayer.currentTime % 60];
    } else {
        _currentTimeLabel.text = [NSString stringWithFormat:@"%d:%d",(int)audioPlayer.currentTime / 60, (int)audioPlayer.currentTime % 60];
    }
    //
    if ((int)audioPlayer.duration % 60 < 10) {
        _totalTimeLabel.text = [NSString stringWithFormat:@"%d:0%d",(int)audioPlayer.duration / 60, (int)audioPlayer.duration % 60];
    } else {
        _totalTimeLabel.text = [NSString stringWithFormat:@"%d:%d",(int)audioPlayer.duration / 60, (int)audioPlayer.duration % 60];
    }
    progressSlider.value = audioPlayer.currentTime / audioPlayer.duration;
    
    [self displaySondWord:audioPlayer.currentTime];//调用歌词函数
    
    //如果播放完，调用自动播放下一首
    if (progressSlider.value > 0.999) {
        [self autoPlay];
    }
    
    //    NSLog(@"%f",audioPlayer.volume);
}



#pragma mark 载入歌曲数组
- (void)initDate {
    
    Music *music1 = [[Music alloc] initWithName:@"梁静茹-偶阵雨" andType:@"mp3"];
    Music *music2 = [[Music alloc] initWithName:@"林俊杰-背对背拥抱" andType:@"mp3"];
    Music *music3 = [[Music alloc] initWithName:@"情非得已" andType:@"mp3"];
    musicArray = [[NSMutableArray alloc]initWithCapacity:5];
    [musicArray addObject:music1];
    [musicArray addObject:music2];
    [musicArray addObject:music3];
    
}


- (void)circle:(UIButton *)sender {
    if (isCircle) {
        circleBtn.alpha = 0.5;
        isCircle = NO;
    } else {
        circleBtn.alpha = 1.0;
        isCircle = YES;
    }
}

- (void)play:(UIButton *)sender{
    if (isPlay) {
        [audioPlayer play];
        [playBtn setBackgroundImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        isPlay = NO;
    } else {
        [audioPlayer pause];
        [playBtn setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
        isPlay = YES;
    }
//    audioPlayer.volume = soundSlider.value;//重置音量,(每次播放的默认音量好像是1.0)

}

#pragma mark 上一首
- (void)aboveMusic:(id)sender {
    if (musicArrayNumber == 0) {
        musicArrayNumber = musicArray.count;
    }
    musicArrayNumber --;
    
//    [self updatePlayerSetting];
}
#pragma mark 下一首
- (void)nextMusic:(id)sender {
    if (musicArrayNumber == musicArray.count - 1) {
        musicArrayNumber = -1;
    }
    musicArrayNumber ++;
    
//    [self updatePlayerSetting];
}
#pragma mark 自动进入下一首
- (void)autoPlay {
    //判断是否允许循环播放
    if (isCircle == YES) {
        if (musicArrayNumber == musicArray.count - 1) {
            musicArrayNumber = -1;
        }
        musicArrayNumber ++;
        
//        [self updatePlayerSetting];
    } else {
        [audioPlayer play];
        [playBtn setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
        isPlay = NO;
    }
}

#pragma mark 得到歌词
- (void)initLRC {
    NSString *LRCPath = [[NSBundle mainBundle] pathForResource:[musicArray[musicArrayNumber] name] ofType:@"lrc"];
    NSString *contentStr = [NSString stringWithContentsOfFile:LRCPath encoding:NSUTF8StringEncoding error:nil];
    //    NSLog(@"contentStr = %@",contentStr);
    NSArray *array = [contentStr componentsSeparatedByString:@"\n"];
    for (int i = 0; i < [array count]; i++) {
        NSString *linStr = [array objectAtIndex:i];
        NSArray *lineArray = [linStr componentsSeparatedByString:@"]"];
        if ([lineArray[0] length] > 8) {
            NSString *str1 = [linStr substringWithRange:NSMakeRange(3, 1)];
            NSString *str2 = [linStr substringWithRange:NSMakeRange(6, 1)];
            if ([str1 isEqualToString:@":"] && [str2 isEqualToString:@"."]) {
                NSString *lrcStr = [lineArray objectAtIndex:1];
                NSString *timeStr = [[lineArray objectAtIndex:0] substringWithRange:NSMakeRange(1, 5)];//分割区间求歌词时间
                //把时间 和 歌词 加入词典
                [LRCDictionary setObject:lrcStr forKey:timeStr];
                [timeArray addObject:timeStr];//timeArray的count就是行数
            }
        }
    }
}
#pragma mark 动态显示歌词
- (void)displaySondWord:(NSUInteger)time {
    //    NSLog(@"time = %u",time);
    for (int i = 0; i < [timeArray count]; i++) {
        
        NSArray *array = [timeArray[i] componentsSeparatedByString:@":"];//把时间转换成秒
        NSUInteger currentTime = [array[0] intValue] * 60 + [array[1] intValue];
        if (i == [timeArray count]-1) {
            //求最后一句歌词的时间点
            NSArray *array1 = [timeArray[timeArray.count-1] componentsSeparatedByString:@":"];
            NSUInteger currentTime1 = [array1[0] intValue] * 60 + [array1[1] intValue];
            if (time > currentTime1) {
                [self updateLrcTableView:i];
                break;
            }
        } else {
            //求出第一句的时间点，在第一句显示前的时间内一直加载第一句
            NSArray *array2 = [timeArray[0] componentsSeparatedByString:@":"];
            NSUInteger currentTime2 = [array2[0] intValue] * 60 + [array2[1] intValue];
            if (time < currentTime2) {
                [self updateLrcTableView:0];
                //                NSLog(@"马上到第一句");
                break;
            }
            //求出下一步的歌词时间点，然后计算区间
            NSArray *array3 = [timeArray[i+1] componentsSeparatedByString:@":"];
            NSUInteger currentTime3 = [array3[0] intValue] * 60 + [array3[1] intValue];
            if (time >= currentTime && time <= currentTime3) {
                [self updateLrcTableView:i];
                break;
            }
            
        }
    }
}

#pragma mark 动态更新歌词表歌词
- (void)updateLrcTableView:(NSUInteger)lineNumber {
    //    NSLog(@"lrc = %@", [LRCDictionary objectForKey:[timeArray objectAtIndex:lineNumber]]);
    //重新载入 歌词列表lrcTabView
    lrcLineNumber = lineNumber;
    [_lrcTableView reloadData];
    //使被选中的行移到中间
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:lineNumber inSection:0];
    [_lrcTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    //    NSLog(@"%i",lineNumber);
}

//更新播放器设置
- (void)updatePlayerSetting {
    //更新播放按钮状态
    [playBtn setBackgroundImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    isPlay = NO;
    
    //更新曲目
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[musicArray[musicArrayNumber] name] ofType:@"mp3"]] error:nil];
    currentMusic = musicArray[musicArrayNumber];
    //更新音量
    audioPlayer.volume = _soundSlider.value;
    //重新载入歌词词典
    timeArray = [[NSMutableArray alloc] initWithCapacity:10];
    LRCDictionary = [[NSMutableDictionary alloc] initWithCapacity:10];
    [self initLRC];
    
    [audioPlayer play];
}

#pragma mark 表视图
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 1) {
        return [musicArray count];
    } else {
        return [timeArray count];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"LRCCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;//该表格选中后没有颜色
    cell.backgroundColor = [UIColor clearColor];
    if (indexPath.row == lrcLineNumber) {
        cell.textLabel.text = LRCDictionary[timeArray[indexPath.row]];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.alpha = 1.0;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
    } else {
        cell.textLabel.text = LRCDictionary[timeArray[indexPath.row]];
        cell.textLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
        cell.textLabel.font = [UIFont systemFontOfSize:13];
    }
    cell.textLabel.backgroundColor = [UIColor clearColor];
    //        cell.textLabel.textColor = [UIColor blackColor];
    
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    
    //        [cell.contentView addSubview:lable];//往列表视图里加 label视图，然后自行布局
    return cell;
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 35;
}
//选中后的响应函数
- (void)playTable:(NSUInteger)tableNumber {
    musicArrayNumber = tableNumber;
    [self updatePlayerSetting];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
